const db = require("../utils/db");
const myexec = require("../utils/exec-shell.js");
const { log } = require("../utils/common.js");

module.exports = {
    valite,
    doAction
};
async function doAction(obj,res) {
  let arr = obj.exec;
  // log('命令组为：\n', arr.join('\n'));
  let data = ["\n∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎执行结果∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎"];
  for (let c of arr) {
    try {
      if (c.includes("{path}")) {
        c = c.replace("{path}", obj.data.path);
      }
      if (obj.data.waitExecComplete) {
        let rsut = await myexec(c);
        log(c, "执行结果：\n", rsut);
      } else {
        myexec(c).then(
          (rsut) => {
            log(c, "执行结果：\n", rsut);
          },
          (err) => {
            log(c, "执行出错：\n", err);
          }
        );
      }
      data.push("执行成功：" + c);
    } catch (e) {
      let msg = "执行出错：" + c;
      log(msg);
      log(e);
      data.push(msg);
    }
  }
  data.push("∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎执行完毕∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎");
  log(data.join("\n"));
  global.wsClients?.forEach((c) => c.send("update"));
  res.send(data.join(","));
};
function valite(commitMsg,password) {
  let msg = commitMsg.trim();
  let pass = password.trim();
  if (!msg) {
    return { msg: "message is null" };
  }
  const configs = db.get("websites");
  let config = configs.find((t) => t.password == pass);
  if (!config) {
    return { msg: "config is not found:" + pass };
  }
  if (config.deployKeyword != msg && config.deployKeyword2 != msg) {
    return { msg: "not need deploy:" + pass };
  }
  if (!config.exec || config.exec.length == 0) {
    return { msg: "config.exec is not setup:" + pass };
  }
  let exec = config.exec;
  if (config.deployKeyword2 === msg) {
    exec = config.exec2;
  }
  return { msg: "ok", exec, data: config };
}
